<?php
class user_Model_Role extends Zend_Db_Table_Abstract  
{
    protected $_name = 'permissions';
    
	public function findByPrimary($id)
	{
		if (!$id)
            return null;
        else
		    return $this->fetchRow('rid = ' . $this->getAdapter()->quote($id, 'INTEGER'));
		        
	}
    
    public function insertRaw($data ,$doValidate = false)
    {
    	return $this->insert($data);
    }
	/*
	 * $idArray:: Array of primary keys
	 */
	public function deleteByPrimary($idArray)
	{
        $db = $this->getAdapter();
        $db->beginTransaction(); //@NOTE: no effect with MyISAM
        try
        {
            $sql1 = "DELETE FROM user_roles WHERE rid IN (". $db->quote($idArray, 'INTEGER') .")" ;
           	$db->query($sql1);
           	$sql2 = "DELETE FROM permissions WHERE rid IN (". $db->quote($idArray, 'INTEGER') .")" ;
           	$db->query($sql2);
            $db->commit();
            return true;
    	}
        catch (Exception $e)
        {
            $db->rollBack();
            return false;
        }
	}

	
	public function saveRaw($row, $data, $id, $doValidate)
	{
	    if((!$row) && (!$id))
	    	return false;
	    else if(!$row)
	       	if(!$row = $this->findByPrimary($id))
	       		return false;
	    if ($doValidate)
	    {
	    	//Validate Data here
	    }
	    //role contains only perm & rname;
	    if (isset($data['perm']))
			$row->perm = $data['perm'];
		if (isset($data['rname']))
			$row->rname = $data['rname'];
		return $row->save();
	}	
	
	
	public function getAllPermissions()
	{
		//role list
        $db = $this->getAdapter();
        $sql = "SELECT * FROM " . $this->_name;
        $rowset = $db->query($sql);
        $rows = $rowset->fetchAll();
        return $rows;
	}
	
    /**
     * @return: aggregate Permissions from the role list
     * @param $roleIds: List of role ids of the form "1,2,3"
     * @see $this->getRoles($id) 
     */
    public function getUserPermissionsFromRoleIds($roleIds)
    {
    	
    	$db = $this->getAdapter();
   		$sql = "SELECT p.perm FROM permissions p WHERE rid IN (" . $db->quote(explode(',', $roleIds), 'INTEGER') .")";
        $perms = $db->fetchAll($sql);
        $userPermission = '';
	    foreach ($perms as $p) 
    	    $userPermission .= ',' . $p['perm'];
    	
		return $userPermission;
    }
    	
}
?>